package com.bishe.controller;



import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bishe.config.DataException;
import com.bishe.entity.User;
import com.bishe.entity.response.R;
import com.bishe.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2024-03-07 14:47:05
 */
@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    @GetMapping("selectClubUser/{id}")
    @ApiOperation("社团成员")
    public R selectClubUser(@PathVariable String id) {
        return R.ok(userService.selectClubUser(id));
    }

    @GetMapping("selectClub/{id}")
    @ApiOperation("我的社团")
    public R selectClub(@PathVariable String id) {
        return R.ok(userService.selectClub(id));
    }

    @GetMapping("otherClub/{id}")
    @ApiOperation("其他社团")
    public R otherClub(@PathVariable String id) {
        return R.ok(userService.otherClub(id));
    }

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param user 查询实体
     * @return 所有数据
     */
    @GetMapping
    public R selectAll(Page<User> page, User user) {
        return R.ok(this.userService.page(page, new QueryWrapper<>(user)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return R.ok(this.userService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param user 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody User user) {
        User one = userService.getOne(new LambdaQueryWrapper<>(User.class).eq(User::getUsername, user.getUsername()));
        if (ObjectUtil.isNotEmpty(one)){
            throw new DataException("该账号用户名已存在");
        }
        return R.ok(this.userService.save(user));
    }

    /**
     * 修改数据
     *
     * @param user 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody User user) {
        return R.ok(this.userService.updateById(user));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public R delete(@RequestParam("idList") List<Long> idList) {
        return R.ok(this.userService.removeByIds(idList));
    }
}

